package com.leejxx.provider.service.impl;

import com.leejxx.blog.exception.BusinessRuntimeException;
import com.leejxx.blog.service.UserService;
import com.leejxx.common.pojo.Permission;
import com.leejxx.common.pojo.Role;
import com.leejxx.common.pojo.User;
import com.leejxx.provider.dao.PermissionDao;
import com.leejxx.provider.dao.RoleDao;
import com.leejxx.provider.dao.UserDao;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

/**
 * @Author LeeJx
 * @ClassName UserServiceImpl
 * @Description TODO
 * @date 2021/2/9 20:15
 * @Version 1.0
 */
@DubboService
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findUserByUserId(Integer id) {
        return userDao.findUserByUserId(id);
    }

    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        List<Role> roles = roleDao.findByUserId(user.getId());

        for (Role role : roles) {
            List<Permission> permissions = permissionDao.findByRoleId(role.getId());
            role.getPermissions().addAll(permissions);
        }
        user.getRoles().addAll(roles);
        return user;
    }

    @Override
    public String findUsernameByPhoneNumber(String phoneNumber) {
        return userDao.findUserNameByPhoneNumber(phoneNumber);
    }

    @Override
    public void userRegister(String username, String password, String phoneNumber) {
        if (null == username || null == password) {
            throw new BusinessRuntimeException("用户名或密码不能为空");
        } else {
            List<String> phoneNumbers = userDao.findAllPhoneNumber();
            if (phoneNumbers.contains(phoneNumber)) {
                throw new BusinessRuntimeException("该手机号已被注册，请直接登录");
            }

            List<String> usernames = userDao.findAllUsernames();
            if (usernames.contains(username)) {
                throw new BusinessRuntimeException("用户名已被使用，请重新输入");
            }

            password = new BCryptPasswordEncoder().encode("{bcrypt}" + password);

            userDao.registerUser(username, password, phoneNumber);
        }
    }
}
